package com.jxwifi.cloud.quickcleanserver.upgrade.DOkHttpUitls;




import android.content.Context;
import android.content.res.AssetManager;
import android.os.Environment;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;

import okhttp3.Response;


public class FileUtils {


    //下载操作
    public static File saveFile2Local(Context context, Response response , String fileName) {

        InputStream inputStream = null;
        OutputStream output = null;
        File file;
        try {
            inputStream = response.body().byteStream();
            file = new File(context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS),fileName);

            output = new FileOutputStream(file);
            byte[] buff = new byte[1024 * 4];
            while (true) {
                int readed = inputStream.read(buff);
                if (readed == -1) {
                    break;
                }
                //write buff
                output.write(buff, 0, readed);
            }
            output.flush();

            return file;
        } catch (IOException e) {
            file = null;
            e.printStackTrace();
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (output != null) {
                try {
                    output.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return null;
    }

    /**
     * 获取用户协议内容
     * @param assets
     * @return
     */
    public static String getString(AssetManager assets) {
        StringBuffer buffer = new StringBuffer();
        // 获取输入流
        BufferedReader reader = null;
        try {
            InputStreamReader inputReader = new InputStreamReader(
                    assets.open("agree.txt"));
            buffer = new StringBuffer();
            // 获取输入流
            reader = new BufferedReader(inputReader);
            // 将返回的数据读到buffer中
            int s;
            while ((s = reader.read()) != -1) {
                buffer.append((char) s);
            }

            return buffer.toString();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            try {
                // 关闭流
                if (null != reader) {
                    reader.close();
                    reader = null;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}
